import {defineStore} from 'pinia'
import {getCurrentUser, login, type UserInfo} from '../api/auth'
import router from '../router'
import {TOKEN_KEY} from "../utils/auth.ts";
import {ElMessage} from "element-plus";

interface AuthState {
    token: string | null
    userInfo: UserInfo | null
    isAuthenticated: boolean
}

export const useAuthStore = defineStore('auth', {
    state: (): AuthState => ({
        token: localStorage.getItem(TOKEN_KEY),
        userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null'),
        isAuthenticated: !!localStorage.getItem(TOKEN_KEY)
    }),
    persist: true,
    actions: {
        async login(account: string, password: string) {
            const response = await login({ account, password })
            this.token = response.token
            this.userInfo = response.user_info
            this.isAuthenticated = true
            localStorage.setItem(TOKEN_KEY, response.token)
            localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
            return response
        },

        async fetchUserInfo() {
            if (!this.token) return
            try {
                if (!!!this.userInfo?.username) {
                    this.userInfo = await getCurrentUser();
                    localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
                }
            } catch (error) {
                this.logout()
            }
        },

        logout() {
            this.token = null
            this.userInfo = null
            this.isAuthenticated = false
            localStorage.removeItem(TOKEN_KEY)
            router.push('/login').then(r => {
                if (r) {
                    ElMessage.error(JSON.stringify(r))
                }
            })
        }
    }
})